import 'dart:typed_data';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/common/event_bus.dart';
import 'package:find_friend/common/play_audio.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/im/custompage/msg_friend_page.dart';
import 'package:find_friend/pages/login&register/model/shared_user_info.dart' show FileModel, SharedUserInfo;
import 'package:flutter/material.dart';
import 'package:gesture_zoom_box/gesture_zoom_box.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:page_transition/page_transition.dart';

class MinePhotoWallPage extends StatefulWidget {
  final String heroTag;
  final List<FileModel> list;
  final bool isowner; // 是否是自己看

  const MinePhotoWallPage({Key key, this.heroTag, this.list, this.isowner = false}) : super(key: key);

  @override
  _MinePhotoWallPageState createState() => _MinePhotoWallPageState();
}

class _MinePhotoWallPageState extends State<MinePhotoWallPage> with SingleTickerProviderStateMixin{

  PageController _controller;
  int index = 0;
  List<FileModel> _list = [];

  @override
  void initState() {
    super.initState();

    int idx = 0;
    if(widget.heroTag != null) idx = int.parse(widget.heroTag.substring(widget.heroTag.length - 1));
    _controller = PageController(initialPage: idx);
    FileModel temp = widget.list[idx];
    if(temp.audiourl != null) {
      _play(temp.audiourl, temp.duration);
    }
    _list = widget.list;
    index = idx;
  }

  
  // 播放图片带的语音
  void _play(String url, int duration) {
    if(url == null) return;
    MyNetWorkPlayer.instance.play(sender: url, audioduration: duration);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

   _saveImage(dynamic data) async {
    final result = await ImageGallerySaver.saveImage(Uint8List.fromList(data));
    if(result != null) {
      AlertTool.showToast("保存成功");
    } else {
      AlertTool.showToast("保存失败,请检查相册权限是否开启");
    }
    print(result);
  }

  _save(String url) {
    Networktool.downloadImage(url, success: (data) {
      _saveImage(data);
    });
  }

  _delet(BuildContext context,int id) {
    AlertTool.showLoadingDialog(context,"正在删除");
    Networktool.request(API.delfile, params: {"id":id, "userinfo": true}, method: NETWORKHTTPMethod.DELETE, success: (data){
      if(data != null){
        setState(() {
          _list.removeWhere((element) => element.id == id);
        });
        SharedUserInfo.saveData(data);
        EventMineBus.instance.commit(EventMineKeys.UpdateMineInfo, null);
        if(_list.length == 0) Navigator.pop(context);
      }
    },
    fail: (msg) => AlertTool.showToast(msg),
    finaly: () => Navigator.of(context).pop()
    );
  }

  _sendToMyFriend(String url) {
    Future.delayed(const Duration(milliseconds: 100)).then((value) => 
      Navigator.of(context).push(PageTransition(
        child: MsgFriendPage(issendImage: true, imgUrl: url,),
        type: PageTransitionType.downToUp
      ))
    );
  }

  void _showMenu() {
    final arrtitles = widget.isowner ? ["发送好友", "保存", "删除"] : ["发送好友", "保存",];
    AlertTool.showBottomDialog(context, arrtitles, onTapIndex: (idx){
      FileModel model = _list[index];
      switch (idx) {
        case 0:{
          _sendToMyFriend(model.url);
        }
          break;
        case 1:
          _save(model.url);
          break;
        case 2:
          _delet(context, model.id);
          break;
      }
      Navigator.of(context).pop();
    });
  }

  @override
  Widget build(BuildContext context) {

    final size = MediaQuery.of(context).size;

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.black,
        leading: IconButton(
          icon: Image.asset("assets/fanhui1.png"),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [
          IconButton(
            icon: Icon(Icons.more_horiz, color: Colors.white),
            onPressed: _showMenu
          )
        ],
      ),
      backgroundColor: Colors.black,
      body: SafeArea(
        child: GestureDetector(
          onVerticalDragUpdate: (details){
            if(details.delta.dy >= 5) Navigator.pop(context);
          },
          onLongPress: _showMenu,
          child: Container(
            child: Stack(
              children: [
                PageView.builder(
                  controller: _controller,
                  scrollDirection: Axis.horizontal,
                  itemCount: _list.length,
                  onPageChanged: (index){
                    setState(() {
                      this.index = index;
                    });
                    _play(_list[index].url, _list[index].duration);
                  },
                  itemBuilder: (context, index) {
                    return GestureZoomBox(
                        maxScale: 5.0,
                        doubleTapScale: 2.0,
                        duration: Duration(milliseconds: 200),
                        child: Container(
                          child: Hero(
                                  tag: widget.heroTag ?? "",
                                  child: CachedNetworkImage(
                                    imageUrl: _list[index].url ?? "",
                                    fit: BoxFit.fitWidth,
                                  ),
                                ),
                        ),
                    );
                  }
                ),
                Positioned(
                  bottom: 0,
                  child: Container(
                    width: size.width,
                    alignment: Alignment.center,
                    child: Text("${index + 1}/${_list.length}", style: instanceTextStyle(14, Colors.white),)
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}